package controllers

import (
	"fmt"
	_ "github.com/beego/beego/v2/client/cache/redis"
	beego "github.com/beego/beego/v2/server/web"
	"house/service"
	"house/utils"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	account := c.GetString("account")
	password := c.GetString("password")
	captcha := c.GetString("captcha")
	isPwd, err := c.GetBool("is_pwd")

	if err != nil {
		Response(c.Controller, nil, fmt.Errorf("is_pwd %v", err))
		return
	}

	if account == "" {
		Response(c.Controller, nil, fmt.Errorf("账号不能为空"))
		return
	}

	if password == "" && isPwd {
		Response(c.Controller, nil, fmt.Errorf("密码不能为空"))
		return
	}

	if captcha == "" && !isPwd {
		Response(c.Controller, nil, fmt.Errorf("验证码不能为空"))
		return
	}

	token, err := service.Login(account, password, captcha)
	if err != nil {
		Response(c.Controller, nil, err)
		return
	}
	Response(c.Controller, token, nil)
	return
}

func (c *UserController) Code() {
	account := c.GetString("account")
	if account == "" {
		Response(c.Controller, nil, fmt.Errorf("account must be set"))
		return
	}

	err := utils.SendCode(account)
	if err != nil {
		Response(c.Controller, nil, err)
		return
	}

	Response(c.Controller, nil, nil)
	return
}
